package com.xzx.study.broadcast;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.xzx.study.R;

public class BroadcastActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TAG-" + BroadcastActivity.class.getSimpleName();
    private Button broadcast_reg;
    private Button broadcast_unreg;
    private Button send_normal_msg;
    private Button send_order_msg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);

        broadcast_reg = findViewById(R.id.broadcast_reg);
        broadcast_unreg = findViewById(R.id.broadcast_unreg);
        send_normal_msg = findViewById(R.id.send_normal_msg);
        send_order_msg = findViewById(R.id.send_order_msg);

        broadcast_reg.setOnClickListener(this);
        broadcast_unreg.setOnClickListener(this);
        send_normal_msg.setOnClickListener(this);
        send_order_msg.setOnClickListener(this);
    }

    private BroadcastReceiver broadcastReceiver;

    @Override
    public void onClick(View v) {
        if (send_normal_msg == v){
            Log.i(TAG, "发送一般广播");
            Intent intent = new Intent("com.xzx.test.broadcast");
            // android 8.0 之后静态注册的广播接收器需要这样才会被接收到,这种相当指定了广播接收器
//            intent.setComponent(new ComponentName("com.xzx.study",
//                                                  "com.xzx.study.broadcast.MyBroadcastReceiver"));
            intent.putExtra("key", "value");
            sendBroadcast(intent);
        } else if (broadcast_reg == v) {
            broadcastReceiver = new MyBroadcastReceiver2();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.xzx.test.broadcast");
            registerReceiver(broadcastReceiver, intentFilter);
        } else if (broadcast_unreg == v) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcast_unreg != null) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
    }
}
